package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.user.dtos.AppLoginDto;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.dtos.UserAuthDto;
import com.heima.user.entity.ApUser;
import com.heima.user.entity.ApUserAuth;
import com.heima.user.entity.ApUserInfo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * APP用户信息表 服务实现类
 * </p>
 *
 * @author RMY
 * @since 2021-11-24
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private BCryptPasswordEncoder encoder;
    /**
     * app端登陆
     * @param appLoginDto
     * @return
     */
    @Override
    public Map<String, Object> login(AppLoginDto appLoginDto) {
        Map<String,Object> map = new HashMap<>();
        Integer userId = 0;
        //1.判断登陆方式 -用户名和密码登陆  -游客登录
        if (StringUtils.isNotBlank(appLoginDto.getPhone())  && StringUtils.isNotBlank(appLoginDto.getPassword())){
            //1.1-用户名和密码登陆：查询数据库是否有此人
            QueryWrapper<ApUser> qw = new QueryWrapper<>();
            qw.lambda().eq(ApUser::getPhone,appLoginDto.getPhone());
            ApUser apUser = getOne(qw);
            if (apUser == null){
                //1.1.3.没有直接返回
                throw new LeadException(AppHttpCodeEnum.AP_USER_NOT_EXIST);
            }
            //1.1.2有的话验证，并返回用户信息和token
            boolean b = encoder.matches(appLoginDto.getPassword(), apUser.getPassword());
            if (!b){
                throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            ApUserInfo apUserInfo = BeanHelper.copyProperties(appLoginDto, ApUserInfo.class);
            map.put("user",apUserInfo);
            userId = apUser.getId();
        }else {
            // 2.-游客登录:返回token
            if (StringUtils.isBlank(appLoginDto.getEquipmentId())){
                throw new LeadException(AppHttpCodeEnum.PARAM_REQUIRE);
            }
        }
        String token = JwtUtils.generateTokenExpireInMinutes(userId, 60);
        map.put("token",token);
        return map;
    }
}
